<script lang="ts">
import { useLocalStorage } from '@peng_kai/kit/libs/vueuse';
import { Modal } from 'ant-design-vue';
import Center from '~/assets/imgs/invitation-spin/center.png';
import Manus from '~/assets/imgs/invitation-spin/manus.png';
import Pointer from '~/assets/imgs/invitation-spin/Pointer.png';
import TurntableBody from '~/assets/imgs/invitation-spin/turntableBody.png';
import { useAutoPopupController } from '~/composables/usePeriodicPopup';
import { handleShare, tipsState, useList } from './hooks';

export const invitationSpin = useAntdModal({
  // eslint-disable-next-line import/no-self-import
  is: defineAsyncComponent(() => import('./InvitationSpin.vue')),
}, {
  width: 'fit-content',
  maskClosable: false,
  closable: false,
  wrapClassName: 'ant-cover__Modal-invitation',
  footer: null,
  maskStyle: {
    backgroundColor: 'rgba(0, 0, 0, 0.75)',
  },
});
</script>

<script setup lang="ts">
withDefaults(defineProps<{
  bg?: boolean;
  bit?: boolean;
}>(), {
  bit: true,
  bg: false,
});
const emits = defineEmits<{
  close: [];
}>();
const invitedSinpStorage = useLocalStorage('invitedSpin', {});
const { deletePopup } = useAutoPopupController();
const authed = useAuthed();
const currentRotation = ref(0); // 旋转角度
const rotationTime = ref(100); // 初始过渡时间
const isSpinning = useBoolean(false); // 转盘是否可用
const slowRotation = ref<number | null>(null); // 自转角度
const winResult = ref<Api.GetData<typeof apis.apiActivityLuckySpinStart>>(); // 中奖结果标
const { refetch, status, list, currency } = useList();
const router = useRouter();
const bp = useAppBreakpoints();
const route = useRoute();
const invitationSpinResults = useAntdModal(
  defineAsyncComponent(() => import('./Results.vue')),
  {
    title: computed(() => ($t('tgOnIdOv92zGkmwV4j0s', { amount: status.value?.max_bonuses ?? 0, currency: currency.value }))),
    wrapClassName: 'ant-cover__Modal-drawer ant-cover__Modal-invited-results',
    centered: true,
    footer: null,
  },
);
// 开始转盘
async function startLottery() {
  winResult.value = await apis.apiActivityInviteStart(undefined);
}

// 更新转盘函数
async function spinWheel() {
  try {
    if (list.value.length <= 0) {
      router.push('/');
      return;
    }
    if (!status.value?.count) {
      handleShare(status?.value?.withdraw_status, true);
      return;
    }
    if (isSpinning.is || (!status.value?.available))
      return;

    isSpinning.setTrue();
    rotationTime.value = 6000;
    stopSlowRotation();
    // 开始抽奖
    await startLottery();
    if (!invitedSinpStorage.value.firstDraw) {
      invitedSinpStorage.value.firstDraw = true;
    }
    const totalSegments = 5; // 奖励总数
    const degreesPerSegment = 360 / totalSegments; // 奖励角度
    const offset = 72;
    const _result = winResult?.value?.result ?? 0;
    const targetDegree = _result * degreesPerSegment + offset;
    const circle = 4; // 圈数
    const currentRot = currentRotation.value % 360;
    let diff = targetDegree - currentRot;
    if (diff < 0)
      diff += 360; // 确保正向旋转
    currentRotation.value += 360 * circle + diff;

    setTimeout(async () => {
      isSpinning.setFalse();
      rotationTime.value = 100;

      refetch();
      if (winResult.value?.result === 3) {
        info($t('6jfKCmooPhDVC17niXzi'));
        return;
      }
      const currency = [{
        symbol: (winResult.value?.circle_list?.[winResult.value.result].currency ?? 'BRL'),
        amount: bignumber(Number((winResult.value?.circle_list?.[winResult.value.result].amount ?? 0))),
      }];
      if ((winResult.value?.circle_list?.[winResult.value.result].amount ?? 0) < 40) {
        await globalPopups.claimSuccess.open({ reward: currency });
      }
      startSlowRotation();
      await invitationSpinResults.open();
      !authed.value && onClose();
    }, rotationTime.value);
  }
  catch (e) {
    startSlowRotation();
    isSpinning.setFalse();
    rotationTime.value = 100;
  }
}

function info(msg: string) {
  Modal.info({
    content: msg,
    footer: null,
    mask: false,
  });
  setTimeout(() => Modal.destroyAll(), 2000);
}
// 开始自转
function startSlowRotation() {
  const rotate = () => {
    currentRotation.value += 0.2;
    slowRotation.value = requestAnimationFrame(rotate);
  };
  slowRotation.value = requestAnimationFrame(rotate);
}
// 停止自转
function stopSlowRotation() {
  if (slowRotation.value !== null)
    cancelAnimationFrame(slowRotation.value);
}
function onClose() {
  emits('close');
  deletePopup('invitedSpin');
  tipsState.value = true;
}

watch(bp, (c) => {
  if (c.ltTabletl && route.name === 'invitation') {
    emits('close');
  }
}, { deep: true });

onMounted(() => {
  tipsState.value = false;
  startSlowRotation();
});
</script>

<template>
  <div class="flex flex-col">
    <div v-if="bp.tabletl || (bp.ltTabletl && route.name !== 'invitation')" class="mb-2.5 flex-center flex-col">
      <p class="graded" :data-text="$t('teWpcQpTvmWDi59pZe1')">
        {{ $t('teWpcQpTvmWDi59pZe1') }}
      </p>
      <p class="graded !text-7.5" :data-text="$t('5xPYsAX9l85FvhYkfX')">
        {{ $t('5xPYsAX9l85FvhYkfX') }}
      </p>
      <I18nT keypath="bO69hCqYsNBxZJb0hcIyj" tag="div" class="text-base text-white leading-8" style="text-shadow: 0px 4px 0px rgba(0, 0, 0, 0.6)">
        <template #amount>
          <span class="text-#78D766">{{ status?.max_amount ?? 0 }}</span>
        </template>
        <template #currency>
          {{ currency }}
        </template>
      </I18nT>
    </div>
    <div class="relative mb-6 flex-center" :class="{ bg }">
      <img :src="TurntableBody" class="w-full object-cover">
      <img :src="Center" class="object-cove absolute left-50% top-28.2% w-60% transform-translate-x--52%" :style="`transform:rotate(${-currentRotation}deg) translateX(-52%);transform-origin:-2%; transition: transform ${rotationTime}ms cubic-bezier(.25,.44,.25,1.06) 0s; `">
      <div class="absolute left-50% top-50% w-20% flex-center transform-translate-x--52% transform-translate-y--10% cursor-pointer" @click="spinWheel">
        <img :src="Pointer" class="object-cove w-full">
        <span class="absolute top-50% transform-translate-y--45% font-900 leading-normal lt-mobilel:text-7.5 mobilel:text-10">
          {{ status?.count ?? 0 }}
        </span>
        <img v-if="!isSpinning.is" :src="Manus" class="custom-animations absolute right--6 top-50% w-18 lt-tabletl:(right--2 top-50% w-55%)">
      </div>
    </div>

    <div v-if="bit && bp.tabletl" class="mb-12 flex-center flex-col">
      <AButton type="primary" class="ant-cover__Button-3d-primary min-w-80" @click="spinWheel">
        {{ $t('uSRrilM173MysAfmlBoVj') }}
      </AButton>
    </div>
    <div v-if="bit" class="flex-center cursor-pointer">
      <i class="i-weui:close2-outlined text-34px text-white" @click="onClose" />
    </div>

    <invitationSpinResults.PresetComponent />
  </div>
</template>

<style lang="scss">
.ant-modal-wrap.ant-cover__Modal-invitation {
  .ant-modal {
    @media bp-lt-tabletl {
      top: 50%;
      transform: translateY(-51.5%);
    }
    .ant-modal-content {
      max-width: 560px;
      min-width: 320px;
      -webkit-box-shadow: none !important;
      -moz-box-shadow: none !important;
      box-shadow: none !important;
      background: linear-gradient(0deg, transparent, transparent) !important;
      border-radius: 16px;
      padding: 0px;
      overflow: hidden;
      position: relative;
    }
  }
}
</style>

<style scoped lang="scss">
.bg {
  z-index: 0;
  &::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: -1;
    background: url(../../../assets/imgs/invitation-spin/bannerFang.png) 50% / cover no-repeat;
    background-color: #1a1b1f;
    -webkit-mask-image: linear-gradient(
      to right,
      rgba(0, 0, 0, 0) 0%,
      rgba(0, 0, 0, 1) 20%,
      rgba(0, 0, 0, 1) 80%,
      rgba(0, 0, 0, 0) 100%
    );
    mask-image: linear-gradient(
      to right,
      rgba(0, 0, 0, 0) 0%,
      rgba(0, 0, 0, 1) 20%,
      rgba(0, 0, 0, 1) 80%,
      rgba(0, 0, 0, 0) 100%
    );
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
    -webkit-mask-size: cover;
    mask-size: cover;
  }
}
.graded {
  --uno: 'text-10 font-900 leading-12 not-italic';

  background: linear-gradient(180deg, #fef356 0%, #fda323 100%);
  background-clip: text;
  color: transparent;
  -webkit-background-clip: text;
  -webkit-background-color: transparent;
  position: relative;
  &::before {
    content: attr(data-text); /* 动态获取文字内容 */
    position: absolute;
    z-index: -1; /* 位于主文字下方 */
    text-shadow: 0px 4px 0px rgba(0, 0, 0, 0.6); /* 自定义阴影效果 */
  }
}
.custom-animations {
  animation: scale-animation 1.5s infinite linear;
}

@keyframes scale-animation {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.3);
  }
}
</style>
